/**
 * 
 */
package co.fitstart.market.web.controller.system;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;

import co.fitstart.market.handler.SmsSender;

/**
 * @author lute
 *
 */
@Controller
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SmsSender smsSender;
    
    /**
     * Sends verify code
     * 
     * @param mobile
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/verify-code", method = RequestMethod.POST)
    public String onSendVerifyCode(@RequestParam("mobile") String mobile) {
        
        Result result = new Result();
        
        // Generate random code in 6 digits
        String code = smsSender.generateVerifyCode(mobile);
    
        // default make sent flag
        boolean sent = smsSender.sendVerifyCode(mobile, code);

        // returns the vtoken
        if(sent) { 
            String token = DigestUtils.sha256Hex(StringUtils.connect(mobile, code, "fitstart"));
            result.success().data("token", token);
        }
        
        return JsonUtils.toJsonString(result);
    
    }

}
